const {Router} = require('express')
const router = new Router()

const GoodsInformationModel = require('../../model/goodsInformation')

// 每一位访问者进行计数
const computedArr = []
// 引入验证模块
const {verifyToken} = require('../../utils/verification')

router.get('/showGoods',function (request, response) {
    const findData = {}
    if (request.query.goodsId) findData._id = request.query.goodsId

    let pageInfo = {}
    if (request.query.pageInfo){
        const {page,limit} = JSON.parse(request.query.pageInfo)
        pageInfo = {
            page: parseInt(page),
            limit: parseInt(limit)
        }
    }else {
        pageInfo = {
            page: 1,
            limit: 10
        }
    }

    const userId = verifyToken(request.get('permission')).data._id
    computedArr[userId] = pageInfo

    const data = {
        code: '200',
        data: 'error',
        msg: '查看商品失败'
    }

    const option = {
        goodsName: 1,
        goodsSecondTitle: 1,
        priceTable: 1,
        goodsThumb: 1,
        firstTitle: 1,
        secondTitle: 1,
    }
    if (request.query.goodsId){
        option.address = 1
        option.goodsDec = 1
        GoodsInformationModel.findOne(findData,option,function (err,doc) {
            if (err) return response.json(data)

            data.data = doc
            data.msg = '查看商品成功'
            return response.json(data)
        })
    }else {
        GoodsInformationModel.find(findData,option).skip( (computedArr[userId].page - 1) * computedArr[userId].limit).limit(computedArr[userId].limit).exec(function (err,doc) {
            if (err) return response.json(data)

            data.data = doc
            data.msg = '查看商品成功'

            if (doc.length != 0){
                return response.json(data)
            }else {
                // 这种情况属于服务器资源不足的时候调用的一种方式
                computedArr[userId] = {
                    page: 1,
                    limit: 10
                }
                GoodsInformationModel.find(findData,option).skip( (computedArr[userId].page - 1) * computedArr[userId].limit).limit(computedArr[userId].limit).exec(function (err,doc){
                    if (err) return response.json(data)

                    data.data = doc
                    data.msg = '查看商品成功'
                    data.page = computedArr[userId].page
                    return response.json(data)
                })
            }
        })
    }
})

module.exports = router
